package com.sky.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sky.exception.OrderBusinessException;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class BaiduMapUtil {
    public static String getLocation(String address, String ak){
        Map map = new HashMap<String, String>();
        map.put("address", address);
        map.put("ak", ak);
        map.put("output","json");

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);
        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            log.info("返回状态码：{}", jsonObject.getString("status"));
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //返回店铺经纬度坐标
        return lat + "," + lng;
    }

    public static Integer getDistance(String origin, String destination, String ak){
        Map map = new HashMap<String, String>();
        map.put("origin", origin);
        map.put("destination", destination);
        map.put("ak", ak);
        log.info("{} -> {}", origin, destination);
        //获取店铺到目标的距离
        String distanceJson = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);
        JSONObject jsonObject = JSON.parseObject(distanceJson);
        if(jsonObject.getInteger("status") != 0){
            log.info("返回状态码：{}", jsonObject.getString("status"));
            throw new OrderBusinessException("店铺距离计算失败");
        }
        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        return (Integer) ((JSONObject) jsonArray.get(0)).get("distance");
    }

}
